package com.zhu.storesmanager.views;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.zhu.storesmanager.utils.Actions;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;

/**
 * 选中日期界面
 */
public class DateView extends TextView implements View.OnClickListener{

	public static final int TYPE_DAY = 0; //天数
	public static final int TYPE_MONTH = 1; //月份

	private static final int DATE_DIALOG_ID = 1; //对话框ID
	private SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd"); //选择天数
	private SimpleDateFormat mDateFormatMonth = new SimpleDateFormat("yyyy-MM"); //选择月份
	//年 月 日
	private int mYear; 
	private int mMonth;
	private int mDay;
	private Activity mActivity = null;
	private int mCurType = TYPE_DAY; //默认天

	public DateView(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}
	
	public DateView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public DateView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 * @param activity
	 * @param type类型
	 * @param reduceMonth 减去月份
	 */
	public void initData(Activity activity, int type, int reduceMonth){
		final Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, reduceMonth);
		mCurType = type;
		mYear = c.get(Calendar.YEAR); 
		mMonth = c.get(Calendar.MONTH); 
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mActivity = activity;
	}

	/*
	 * (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		mActivity.showDialog(DATE_DIALOG_ID);
	}

	/**
	 * 日期控件的事件
	 */

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			if(Actions.DEBUG){
				Log.e("zhu", mYear + "-" + mMonth +"-" +mDay);
			}
			updateDateDisplay();
		}
	};

	/**
	 * 创建日期选择dialog
	 * @param id 创建dialogID
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	public Dialog onCreateDialog(int id) {
		switch (id) {
			case DATE_DIALOG_ID:
			return new DatePickerDialog(mActivity, mDateSetListener, mYear, mMonth, mDay);
		}
		return null;
	}

	 /**
     * 从当前Dialog中查找DatePicker子控件
     * 
     * @param group
     * @return
     */
    private DatePicker findDatePicker(ViewGroup group) {
        if (group != null) {
            for (int i = 0, j = group.getChildCount(); i < j; i++) {
                View child = group.getChildAt(i);
                if (child instanceof DatePicker) {
                    return (DatePicker) child;
                } else if (child instanceof ViewGroup) {
                    DatePicker result = findDatePicker((ViewGroup) child);
                    if (result != null)
                        return result;
                }
            }
        }
        return null;
    }

	/**
	 * 准备dialog数据
	 * (non-Javadoc)
	 * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
	 */
	 public void onPrepareDialog(int id, Dialog dialog) { 
	    switch (id) { 
	    	case DATE_DIALOG_ID:
	    		if (mCurType == TYPE_MONTH) {
					int SDKVersion = Actions.getSDKVersionNumber();
					DatePicker dp = findDatePicker((ViewGroup) dialog.getWindow()
							.getDecorView());// 隐藏日
					if (dp != null) {
						if (SDKVersion < 11) {
							((ViewGroup) dp.getChildAt(0)).getChildAt(2)
									.setVisibility(View.GONE);
						}
						if (SDKVersion > 14) {
							((ViewGroup) ((ViewGroup) dp.getChildAt(0))
									.getChildAt(0)).getChildAt(2).setVisibility(
									View.GONE);
						}
					}
				}
	    		((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay); 
	        break;
	     }
	 }

	/**
	 * 更新日期显示
	 */
	private void updateDateDisplay() {
		if(mCurType == TYPE_MONTH){
			this.setText(new StringBuilder().append(mYear).append("-")
					.append((mMonth + 1) < 10 ? "0" + (mMonth + 1) : (mMonth + 1)));
		}else{
			this.setText(new StringBuilder().append(mYear).append("-")
					.append((mMonth + 1) < 10 ? "0" + (mMonth + 1) : (mMonth + 1))
					.append("-").append((mDay < 10) ? "0" + mDay : mDay));
		}
	}

	/**
	 * 返回格式
	 * @return mDateFormat
	 */
	public SimpleDateFormat getSimpleDateFormat(){
		return  mDateFormat;
	}

	/**
	 * 获取选中时间this
	 * @return time 返回获取时间
	 */
	public long getTime(){
		long time = 0;
		try {
			if(mCurType == TYPE_MONTH){
				time = mDateFormatMonth.parse(getText().toString()).getTime();
			}else{
				time = mDateFormat.parse(getText().toString()).getTime();
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			return time;
		}
	}

	/**
	 * 设置选中日期
	 */
	public void setSavedData(long date){
		if(date > 0){
			String text = null;
			if(mCurType == TYPE_MONTH){
				text = mDateFormatMonth.format(new Date(date));
			}else{
				text = mDateFormat.format(new Date(date));
			}
			setText(text);
			String[] temArr = text.split("-");
			mYear = Integer.parseInt(temArr[0]);
			mMonth = Integer.parseInt(temArr[1]) -1;
			if(temArr.length == 3){
				mDay = Integer.parseInt(temArr[2]);	
			}
		}
	}
}
